package com.app.util.file.struct;

import java.io.File;
import java.io.IOException;

import com.app.util.file.txt.LineReader;
import com.app.util.param.Param;
import com.app.util.type.IntegerUtil;

public class StructFileReader {

	private Params params = new Params();
	private LineReader lineReader;

	/**
	 * 构造一个结构文件存储类
	 * 
	 * @param file
	 * @param charset
	 * @throws IOException
	 */
	public StructFileReader(File file, String charset) throws IOException {
		lineReader = new LineReader(file, charset);
	}

	/** 
	 * 构造一个结构文件存储类
	 * 
	 * @param file
	 * @throws IOException
	 */
	public StructFileReader(File file) throws IOException {
		lineReader = new LineReader(file);
		readParams();
	}

	public Params getParams() {
		return params;
	}

	private void readParams() throws IOException {
		String line;
		boolean first = true;
		int i = 0;
		int count = 0;
		while (null != (line = lineReader.next())) {
			Param header = Params.parseParam(line);
			if (first) {
				first = false;
				if (null == header//
						|| null == header.getValue()//
						|| !header.getName().equals("# header, count")//
						|| !IntegerUtil.isInt(header.getValue())//
				) {
					throw new DamagedException("'" + lineReader.getFile() + "' structure is damaged");
				}
				count = IntegerUtil.parseInt(header.getValue());
				continue;
			}
			if (null == header) {
				continue;
			}
			params.add(header);
			if (++i == count) {
				break;
			}
		}
	}

	/**
	 * 读出一行字符串
	 * 
	 * @return
	 * @throws IOException
	 */
	public String readLine() throws IOException {
		return lineReader.next();
	}

	public void close() throws IOException {
		lineReader.close();
	}

	public LineReader getLineReader() {
		return lineReader;
	}
}
